<template>
  <!-- 转领导批示dialog-->
  <el-dialog
    title="转领导批示"
    :visible="visible"
    @open="openFunc"
    :before-close="resetFun"
    :destroy-on-close="true"
    class="dialogStyle"
    width="560px"
  >
    <el-form
      :model="ruleForm"
      :rules="rules"
      ref="ruleForm"
      label-width="76px"
      :loading="loading"
    >
      <el-form-item label="选择领导" prop="leaderId" class="select-leader">
        <el-select
          v-model="selectedValue"
          multiple
          size="medium"
          collapse-tags
          popper-class="tree-select"
          @change="changeData"
        >
          <el-option :value="selectedValue">
            <el-tree
              :data="nameList"
              node-key="userId"
              :default-expand-all="true"
              ref="tree"
              check-strictly
              show-checkbox
              @click.stop.native
              :props="defaultProps"
              @check-change="handleCheckChange"
            >
              <span
                class="custom-tree-node"
                slot-scope="{ node, data }"
                :title="node.label"
              >
                <svg-icon
                  v-if="data.leaf == true"
                  icon-class="usericon"
                ></svg-icon>
                <span>{{ node.label }}</span>
              </span>
            </el-tree>
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="请示内容" class="small" prop="desc">
        <el-input
          type="textarea"
          v-model="ruleForm.desc"
          @input="ruleForm.desc = ruleForm.desc.replace(/\s+/g, '')"
          placeholder="请输入内容"
          rows="9"
          resize="none"
        ></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button
        @click="submitFun('ruleForm')"
        style="margin-right: 10px"
        type="primary"
        >提 交</el-button
      >
      <el-button @click="resetFun">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { $store, $getUrlParam } from "@/utils/public";
import {
  addLeaderAudit,
  getLeaderByTenantIdShowTree,
} from "@/api/modules/eventManagement/eventDialog/instructionDialog";
import TreeSelect from "@/components/TreeSelect";

export default {
  name: "instructionsDialog",
  components: {
    TreeSelect,
  },
  data() {
    return {
      loading: false,
      ruleForm: {
        leaderId: "",
        desc: "",
      },
      resetCascader: 0,
      nameList: [],
      selectedValue: [],
      rules: {
        leaderId: [
          {
            required: true,
            message: "请选择领导",
            trigger: ["blur", "change"],
          },
        ],
        desc: [
          {
            required: true,
            message: "请输入请示内容",
            trigger: ["blur", "change"],
          },
        ],
      },
      defaultProps: {
        label: "userName",
        value: "userId",
        disabled: (data, node) => {
          //只支持单选，父节禁用
          if (data.children && data.children.length > 0) {
            return true;
          } else {
            return false;
          }
        },
      },
    };
  },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    orderData: {
      type: Object,
      default: () => ({}),
    },
  },
  watch: {
    nameList: () => {
      this.resetCascader++;
    },
  },
  methods: {
    openFunc() {
      this.loading = true;
      let _this = this;
      //领导列表
      let params = {
        roleFlag: "8", //5-调度人员；8-领导
        provinceId: _this.orderData.provinceId,
        cityId: _this.orderData.cityId,
        countyId: _this.orderData.countyId,
        orgId: $store.get("$loginInfo").orgId,
        deviceCode: this.orderData.deviceCode,
        warningSource: this.orderData.warningSource,
        warningTypeId: this.orderData.warningTypeId,
      };
      if (_this.$store.getters.userInfo.tenantId) {
        params.tenantId = _this.$store.getters.userInfo.tenantId;
      }
      getLeaderByTenantIdShowTree(params).then((resp) => {
        this.loading = false;
        if (resp && resp.code == 200) {
          this.deepHandleTree(resp.data);
          _this.nameList = resp.data;
        } else {
          $message.warning(resp.mess);
        }
      });
      // getUserByTenantIdNew(params).then(resp => {
      //   if (resp && resp.code == 200) {
      //     _this.nameList = resp.data;
      //   } else {
      //     _this.$message.warning(resp.mess);
      //   }
      // });
      // $v.post(_this, urlBdm + "/gridKeeper/getUserByTenantIdNew", params, function (resp) {
      //   if (resp && resp.resultStat == "SUCCESS") {
      //     _this.nameList = resp.data;
      //   } else {
      //     $v.message({
      //       type: resp.resultStat,
      //       mess: resp.mess,
      //       data: resp.data
      //     });
      //   }
      // });
    },
    deepHandleTree(item) {
      for (let i = 0; i < item.length; i++) {
        if (!item[i].userId) {
          item[i].userId = item[i].deptId + "" + i;
        }
        if (!item[i].userName) {
          item[i].userName = item[i].deptName;
        }
        if (item[i].children && item[i].children.length > 0) {
          this.deepHandleTree(item[i].children);
        } else {
          item[i].leaf = true;
        }
      }
    },
    //提交
    submitFun(formName) {
      let _this = this;
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (_this.ruleForm.desc.length > 255) {
            $message.warning("请示内容不能超过255字！");
            return;
          }
          let params = {
            tenantId: _this.$store.getters.userInfo.tenantId,
            orderId: _this.orderData.warningOrderId,
            userId: $store.get("$loginInfo").userId,
            leaderId: _this.ruleForm.leaderId,
            content: _this.ruleForm.desc,
            msgNotifyType: _this.orderData.msgNotifyType,
          };
          addLeaderAudit(params).then((resp) => {
            let msgId = {
              id: this.orderData.warningOrderId,
              status: this.orderData.orderStatus,
            };
            this.$store.dispatch("closeSocketMsg", msgId);
            if (resp && resp.code == 200) {
              $message.success("转领导批示成功");
              _this.onSuccess();
              _this.resetForm();
            } else {
              $message.warning(resp.mess);
            }
          });
          this.$emit("update:visible", false);
        }
      });
    },
    onSuccess() {
      const url =
        $getUrlParam("pageType") === "false"
          ? "/eventManagement"
          : "/eventManagement/myEvent";
      this.$close(url);
    },
    resetFun() {
      this.resetForm();
      this.$emit("update:visible", false);
    },
    resetForm() {
      this.ruleForm = {
        leaderId: "",
        desc: "",
      };
      this.selectedValue = [];
    },
    handleCheckChange(data, checkbox, node) {
      if (checkbox) {
        this.$refs.tree.setCheckedKeys([data.userId]);
        this.ruleForm.leaderId = [data.leaderId];
        this.selectedValue = [data.userName];
        this.ruleForm.leaderId = this.$refs.tree.getCheckedKeys().toString(); //不加上toString()会报：期望一个数字或者字符串，结果返回的是数组
      } else {
        this.ruleForm.leaderId = this.$refs.tree.getCheckedKeys().toString();
        if (this.ruleForm.leaderId.length == 0) {
          this.ruleForm.leaderId = [];
          this.selectedValue = [];
        }
      }
    },
    changeData(e) {
      this.ruleForm.leaderId = "";
      this.$refs.tree.setCheckedKeys([]);
    },
  },
};
</script>

<style lang="scss" scoped>
/deep/ .el-dialog__body {
  padding: 12px 60px 0;
}
/deep/ .el-row {
  margin-bottom: 1.5%;
}
/deep/ .el-form-item__error {
  position: relative;
}
/deep/.select-leader .el-form-item__error {
  position: absolute;
  top: 35px;
  left: 5px;
}
/deep/ .submitClass {
  background: #ff6a6c !important;
  color: #ffffff !important;
}

/deep/.el-tree-node__children .el-checkbox {
  display: block;
}
.tree-select li {
  padding: 0;
}
.tree-select .el-select-dropdown__list .el-select-dropdown__item {
  height: 254px;
  overflow-y: scroll;
}
.tree-select .el-select-dropdown__list .el-select-dropdown__item.hover {
  background: #fff;
  padding: 0px;
}
.tree-select {
  .el-select-dropdown__list {
    .el-select-dropdown__item {
      height: 254px;
      overflow-y: scroll;
      background: #fff;
      padding: 0px;
    }
  }
  .el-scrollbar__thumb {
    display: none;
  }
  .el-select-dropdown__item::after {
    display: none;
  }
}
.dialogStyle {
  /deep/ .el-dialog {
    border-radius: 4px;
  }
  /deep/ .el-dialog__header {
    padding: 12px;
  }
  /deep/ .el-dialog__footer {
    padding: 12px;
  }
  /deep/ .el-textarea__inner {
    height: 206px;
  }
  /deep/ .el-form-item .el-form-item__label {
    padding-right: 6px;
  }
}
</style>
<style>
.el-popper.tree-select {
  margin-top: 1px !important;
  overflow: hidden;
}
</style>
